import {
    Button,
    Card,
    Col,
    Form,
    Input,
    Row,
    Space,
    Table,
} from "antd";
import {SpaceBox} from "@/components/space/SpaceBox.tsx";
import {useCallback, useEffect, useReducer, useRef, useState} from "react";
import type {ReducerActionType} from "@/types/commonType.ts";
import type {UserFormSearchType, UserItemType} from "@/types/userType.ts";
import {systemApi} from "@/services/system.ts";
import {TABLE_TOOLS_STYLE} from "@/utils/constant.ts";
import { EditOutlined, ImportOutlined, PlusOutlined} from "@ant-design/icons";
import {formatterTime, getBaseUrl} from "@/utils";
import {ImportTemplate} from "@/components/importTemplate/ImportTemplate.tsx";
import {DangerButton} from "@/components/button/DangerButton.tsx";

type UserStateType = {
    collapse: boolean
    formData: UserFormSearchType
    pagination: {
        page: number,
        pageSize: number,
        totale: number
    }
}

const {Item, useForm} = Form

const {Column} = Table

const userState: UserStateType = {
    collapse: false,
    formData: {
        user_name: '',
        nick_name: '',
        phone: '',
        email: '',
        sex: 2,
        status: 2,
    },
    pagination: {
        page: 1,
        pageSize: 10,
        totale: 0
    }
}

const reducer = (state: UserStateType, action: ReducerActionType) => {
    const {payload, type} = action
    switch (type) {
        case 'SET_COLLAPSE':
            return {
                ...state,
                ...payload
            }
        case 'SET_FORMDATA':
            return {
                ...state,
                ...payload
            }
        case 'SET_PAGINATION':
            return {
                ...state,
                ...payload
            }
        default:
            return state
    }
}

const action = getBaseUrl() + '/system/user/export'

const User = () => {
    const [list, setList] = useState<UserItemType[]>([])

    const [form] = useForm()

    const importTemplateRef = useRef<{
        showModal: () => void,
        hideModal: () =>void
    }>(null)

    const [state, dispatch] = useReducer(reducer, userState)
    // 展开折叠方法
    const SET_COLLAPSE = useCallback(() => {
        dispatch({
            type: 'SET_COLLAPSE',
            payload: {
                collapse: !state.collapse
            }
        })
    }, [state.collapse])

    // 查询
    const onFinish = useCallback((e: UserFormSearchType) => {
        console.log(e)
        dispatch({
            type: 'SET_FORMDATA',
            payload: {
                formData: {
                    ...e,
                    // page: 1,
                    // pageSize: 10
                }
            }
        })
    }, [])

    // 重置
    const onReset = useCallback(() => {
        form.setFieldsValue({
            user_name: '',
            nick_name: '',
            phone: '',
            email: '',
            sex: 2,
            status: 2,
        })
        dispatch({
            type: 'SET_FORMDATA',
            payload: {
                formData: {
                    user_name: '',
                    nick_name: '',
                    phone: '',
                    email: '',
                    sex: 2,
                    status: 2,
                }
            }
        })
    }, [form])

    useEffect(() => {
        onReset()
    }, [form, onReset]);

    useEffect(() => {
        getList();
    }, [state.formData])


    function getList () {
        systemApi.userPageList({
            data: state.formData,
            page: state.pagination.page,
            pageSize: state.pagination.pageSize
        }).then(res => {
            if (res.code === 200) {
                dispatch({
                    type: 'SET_PAGINATION',
                    payload: {
                        pagination: {
                            page: res.data.page,
                            pageSize: res.data.pageSize,
                            total: res.data.total
                        }
                    }
                })
                setList(res.data.list)
            }
        })
    }

    const handleDelete = (id: number) => {
        console.log(id)
    }

    return (
        <SpaceBox>
            <Card>
                <Form onFinish={onFinish} form={form}>
                    <Row gutter={16}>
                        <Col span={6}>
                            <Item<UserFormSearchType> label={'账号'} name={'user_name'}>
                                <Input></Input>
                            </Item>
                        </Col>
                        <Col span={6}>
                            <Item<UserFormSearchType> label={'用户名称'} name={'nick_name'}>
                                <Input></Input>
                            </Item>
                        </Col>
                        {
                            state.collapse && (
                                <>
                                    <Col span={6}>
                                        <Item<UserFormSearchType> name={'phone'} label={'手机号'}>
                                            <Input></Input>
                                        </Item>
                                    </Col>
                                    <Col span={6}>
                                        <Item<UserFormSearchType> name={'email'} label={'邮箱'}>
                                            <Input></Input>
                                        </Item>
                                    </Col>
                                    <Col span={6}>
                                        <Item<UserFormSearchType> name={'sex'} label={'性别'}>
                                            <Input></Input>
                                        </Item>
                                    </Col>
                                    <Col span={6}>
                                        <Item<UserFormSearchType> name={'status'} label={'状态'}>
                                            <Input></Input>
                                        </Item>
                                    </Col>
                                </>
                            )
                        }
                        <Col span={6}>
                            <Item>
                                <Space>
                                    <Button danger onClick={SET_COLLAPSE}>
                                        {state.collapse ? '收起' : '展开'}
                                    </Button>
                                    <Button type={"primary"} htmlType={'submit'}>查询</Button>
                                    <Button htmlType={'reset'} onClick={onReset}>重置</Button>
                                </Space>
                            </Item>
                        </Col>
                    </Row>
                </Form>
            </Card>
            <Card>
                <Space style={TABLE_TOOLS_STYLE}>
                    <Button
                        type={"primary"}
                        icon={<PlusOutlined/>}
                    >新增</Button>
                    <Button
                        color={'purple'}
                        variant={"solid"}
                        icon={<ImportOutlined />}
                        onClick={() => {
                            importTemplateRef.current?.showModal()
                        }}
                    >导入</Button>
                </Space>
                <Table<UserItemType>
                    size={'small'}
                    dataSource={list}
                    pagination={{
                        position: ['bottomRight'],
                        total: state.pagination.totale,
                        current: state.pagination.page,
                        pageSize: state.pagination.pageSize,
                        showTotal: (total) => `total ${total}`,
                        onChange: (e) => {
                            console.log(e)
                        }
                    }}
                    bordered
                    rowKey={'id'}
                >
                    <Column
                        title={'用户名称'}
                        align={'center'}
                        key={'nick_name'}
                        dataIndex={'nick_name'}
                    />
                    <Column
                        title={'账号'}
                        align={'center'}
                        key={'user_name'}
                        dataIndex={'user_name'}
                    />
                    <Column
                        title={'电话'}
                        align={'center'}
                        key={'phone'}
                        dataIndex={'phone'}
                    />
                    <Column
                        title={'邮箱'}
                        align={'center'}
                        key={'email'}
                        dataIndex={'email'}
                    />
                    <Column
                        title={'头像'}
                        align={'center'}
                        key={'avatar'}
                        dataIndex={'avatar'}
                    />
                    <Column
                        title={'性别'}
                        align={'center'}
                        key={'sex'}
                        dataIndex={'sex'}
                    />
                    <Column
                        title={'状态'}
                        align={'center'}
                        key={'status'}
                        dataIndex={'status'}
                    />
                    <Column
                        title={'创建时间'}
                        align={'center'}
                        key={'create_time'}
                        dataIndex={'create_time'}
                        render={(value: number) => formatterTime(value)}
                    />
                    <Column
                        title={'操作'}
                        align={'center'}
                        render={(_, record) => (
                            record.user_name !== 'admin' &&
                            <Space>
                                <Button
                                    type={'link'}
                                    icon={<EditOutlined />}
                                    onClick={() => {
                                        console.log(record)
                                    }}
                                >修改</Button>
                                <DangerButton
                                    description={'确认是否删除当前用户吗？'}
                                    onConfirm={() => handleDelete(record.id)}
                                />
                            </Space>
                        )}
                    />
                </Table>
            </Card>
            <ImportTemplate
                getList={getList}
                action={action}
                fileName={'用户导入模板.xlsx'}
                ref={importTemplateRef}
                title={'用户导入'}
                template={'user'}
            />
        </SpaceBox>
    )
}


export default User